package com.blacktry.controller;

import com.blacktry.entity.enums.OprLogConst;
import com.blacktry.entity.model.Admin;
import com.blacktry.entity.model.ApiResult;
import com.blacktry.entity.model.request.LoginRequest;
import com.blacktry.service.AdminService;
import com.blacktry.utils.ApiResultHandler;
import com.blacktry.utils.log.OperLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;

@Api(tags = "登录管理接口")
@RestController
public class LoginController {

    @Autowired
    private AdminService adminService;


    @OperLog(operModul = "用户管理-登陆之后返回token",operType = OprLogConst.SELECT,operDesc = "登陆之后返回token")
    @ApiOperation(value = "登陆之后返回token")
    @PostMapping("/login")
    public ApiResult<Map<String,String>> login(@RequestBody LoginRequest loginRequest, HttpServletRequest request){
        return adminService.login(loginRequest,request);
    }


    @OperLog(operModul = "用户管理-获取当前登录用户的信息",operType = OprLogConst.SELECT,operDesc = "获取当前登录用户的信息")
    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal){
        if(null == principal){
            return null;
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByUserName(username);
        admin.setPassword(null);
        admin.setRoles(adminService.getRoles(admin.getId()));
//        return ApiResultHandler.buildApiResult(200,"成功",admin);
        return admin;
    }
    @OperLog(operModul = "用户管理-退出登录",operType = OprLogConst.SELECT,operDesc = "退出登录")
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public ApiResult logout(){
        return ApiResultHandler.buildApiResult(200,"成功","注销成功!");
    }
}
